package com.gitee.wsl.android.ui.signature.pan

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.view.MotionEvent


/***
 * 名称：Eraser<br></br>
 * 描述：橡皮擦
 * 最近修改时间：
 * @since 2018/5/7
 * @author king
 */
class Eraser(paintWidth: Float) {

    private val eraserPaint: Paint by lazy {
        Paint().apply {
            style = Paint.Style.STROKE
            strokeJoin = Paint.Join.ROUND
            strokeCap = Paint.Cap.ROUND
            strokeWidth = paintWidth
            isFilterBitmap = true
            color = Color.WHITE
            isDither = true
            xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
            isAntiAlias = true
        }
    }

    /**
     * 画笔路径
     */
    private val mPath: Path = Path()

    /**
     * 记录上一个点的坐标
     */
    private var mLastX = 0f
    private var mLastY = 0f


    //    public void setPaintWidth(int width) {
    //        eraserPaint.setStrokeWidth(width);
    //    }
    fun handleEraserEvent(event: MotionEvent, canvas: Canvas): Boolean {
        val x = event.x
        val y = event.y
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                mLastX = x
                mLastY = y
                mPath.reset()
                mPath.moveTo(x, y)
            }

            MotionEvent.ACTION_MOVE -> {
                mPath.quadTo(mLastX, mLastY, (x + mLastX) / 2, (y + mLastY) / 2)
                canvas.drawPath(mPath, eraserPaint)
                mLastX = x
                mLastY = y
            }

            MotionEvent.ACTION_CANCEL -> {}
            MotionEvent.ACTION_UP -> {
                mPath.lineTo(mLastX, mLastY)
                canvas.drawPath(mPath, eraserPaint)
            }
        }
        return true
    }
}
